<template>
    <div>
      <!--    面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>修改用户信息（密码、姓名）</el-breadcrumb-item>
      </el-breadcrumb>
<!--      卡片-->
      <el-card>
        <!--      搜索与添加区域-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input placeholder="请输入内容" v-model="queryInfo.searchInfo" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="13">
            <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              查询用户信息<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="a">所有学生信息</el-dropdown-item>
                <el-dropdown-item command="b" divided>所有教师信息</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
<!--        用户列表区域-->
        <el-table :data="pageuserlist" :stripe="true">
          <el-table-column fixed type="index" label="#"></el-table-column>
<!--          <el-table-column  width="60" prop="id" label="#"></el-table-column>-->
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="name" label="姓名">
            <template slot-scope="scope">
              <el-popover>
                <p>姓名：{{scope.row.name}}</p>
                <hr>
                <p>ID: {{ scope.row.id }}</p>
                <p>{{scope.row.role === 'student' ? '学生编号:' : (scope.row.role === 'teacher' ? '教师编号:' : '')}} {{scope.row.role === 'student' ? scope.row.sid : (scope.row.role === 'teacher' ? scope.row.tid : '')}}</p>
                <p>权限：{{scope.row.perms}}</p>
                <div slot="reference">
                  {{scope.row.name}}
                </div>
              </el-popover>
            </template>
          </el-table-column>
<!--          <el-table-column prop="perms" label="权限"></el-table-column>-->
<!--          <el-table-column prop="role" label="角色"></el-table-column>-->
          <el-table-column prop="role" label="角色" :filters="[{text:'学生', value: 'student'},{text:'教师', value: 'teacher'},{text:'管理员', value: 'admin'}]"
          :filter-method="filterTag"
          filter-placement="bottom-end">
            <template slot-scope="scope">
              <el-tag size="medium"
                :type="scope.row.role === 'student' ? 'primary' : 'success'" disable-transitions >{{scope.row.role}}</el-tag>
            </template>
          </el-table-column>
<!--        操作-->
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
<!--              修改密码按钮-->
              <el-tooltip effect="dark" content="修改密码" placement="top">
                <el-button type="primary" icon="el-icon-edit" size="mini" :enterable="false" @click="showEditDialog(scope.row.username)"></el-button>
              </el-tooltip>
<!--              修改名字按钮-->
              <el-tooltip effect="dark" content="修改姓名" placement="top">
                <el-button type="info" icon="el-icon-edit" size="mini" plain :enterable="false" v-if="scope.row.role === 'student'" @click="showNameDialog(scope.row.sid,scope.row.username,scope.row.role)"></el-button>
                <el-button type="info" icon="el-icon-edit" size="mini" :enterable="false" v-else-if="scope.row.role === 'teacher'" @click="showNameDialog(scope.row.tid,scope.row.username,scope.row.role)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--      分页区域-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!--    修改用户信息的对话框-->
      <el-dialog
        title="修改用户密码"
        :visible.sync="editDialogVisible"
        width="50%" @close="editDialogClosed">
        <!--      内容主体区域-->
        <el-form :model="editForm" status-icon :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newpass">
            <el-input type="password" show-password placeholder="请设置新密码" v-model="editForm.newpass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" show-password @keyup.enter.native="editPwds" placeholder="请确认新密码" v-model="editForm.checkPass" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <!--      底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetEdit">重置修改</el-button>
          <el-button type="primary" @click="editPwds">确定修改</el-button>
        </span>
      </el-dialog>
      <!--    修改用户姓名的对话框-->
      <el-dialog
        title="修改用户姓名"
        :visible.sync="nameDialogVisible"
        width="50%" @close="nameDialogClosed">
        <!--      内容主体区域-->
        <el-form :model="nameForm" status-icon :rules="nameFormRules" ref="nameFormRef" label-width="100px">
          <el-form-item :label="nameForm.role === 'student' ? '学生编号' : '教师编号'">
            <el-input v-model="nameForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="nameForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="新名字" prop="name">
            <el-input v-model="nameForm.name" placeholder="请输入名字" v-if="nameForm.role === 'student'" @keyup.enter.native="editName" autocomplete="off"></el-input>
            <el-input v-model="nameForm.name" placeholder="请输入名字" v-else-if="nameForm.role === 'teacher'" @keyup.enter.native="editTechName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <!--      底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetName">重置修改</el-button>
          <el-button type="primary" v-if="nameForm.role === 'student'" @click="editName">确定修改</el-button>
          <el-button type="primary" v-else-if="nameForm.role === 'teacher'" @click="editTechName">确定修改</el-button>
        </span>
      </el-dialog>
<!--      查询所有教师用户信息-->
      <el-dialog width="50%" title="所有教师用户信息" :visible.sync="Techopen">
        <el-table :data="TechAllinfo" stripe height="260" :default-sort = "{prop: 'username', order: 'ascending'}">
          <el-table-column property="id" label="班级编号" width="150" sortable></el-table-column>
          <el-table-column property="username" label="教师工号" width="200" sortable></el-table-column>
          <el-table-column property="name" label="教师姓名"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="Techopen = false">取 消</el-button>
          <el-button type="primary" @click="Techopen = false">确 定</el-button>
        </span>
      </el-dialog>
<!--      查询所有学生用户信息-->
      <el-dialog width="50%" title="所有学生用户信息" :visible.sync="Stuopen">
        <el-table :data="StuAllinfo" stripe  height="260" :default-sort = "{prop: 'username', order: 'ascending'}">
          <el-table-column property="id" label="编号" width="150" sortable></el-table-column>
          <el-table-column property="username" label="学生学号" width="200" sortable></el-table-column>
          <el-table-column property="name" label="学生姓名"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="Stuopen = false">取 消</el-button>
          <el-button type="primary" @click="Stuopen = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 密码校验
    var Pass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        callback()
      }
    }
    var Pass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.editForm.newpass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var name = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新名字, 不能为空'))
      } else {
        callback()
      }
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 模糊搜索
        searchInfo: '',
        // 当前页数
        pagenum: 1,
        pagesize: 5
      },
      userlist: [],
      total: 0,
      // pageuserlist: [],
      // 控制修改对话框的显示与否
      editDialogVisible: false,
      // 查询到的用户密码信息
      editForm: {
        username: '',
        newpass: '',
        checkPass: ''
      },
      editFormRules: {
        newpass: [
          {
            require: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '密码长度不少于6位',
            trigger: 'blur'
          },
          {
            validator: Pass,
            trigger: 'blur'
          }
        ],
        checkPass: [
          {
            require: true,
            message: '确认新密码不能为空',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '密码长度不少于6位',
            trigger: 'blur'
          },
          {
            validator: Pass2,
            trigger: 'blur'
          }
        ]
      },
      // 修改名字
      nameDialogVisible: false,
      nameForm: {
        id: '',
        username: '',
        name: '',
        role: ''
      },
      nameFormRules: {
        name: [{
          validator: name,
          trigger: 'blur'
        }]
      },
      Techopen: false,
      TechAllinfo: {
        id: '',
        username: '',
        name: ''
      },
      Stuopen: false,
      StuAllinfo: {
        id: '',
        username: '',
        name: ''
      }
    }
  },
  created () {
    this.getUserList()
    this.getAllTechInfo()
    this.getAllStuinfo()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('/user/allUser')
      if (res.status !== 200) {
        return this.$message.error('获取用户列表失败!')
      }
      this.userlist = res.data
      // 实现分页
      // this.pageuserlist = this.userlist.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
      this.total = res.data.length
      // console.log(res)
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 重置修改密码输入框
    resetEdit () {
      this.$refs.editFormRef.resetFields()
    },
    resetName () {
      this.$refs.nameFormRef.resetFields()
    },
    // 展示修改用户密码的对话框
    showEditDialog (username) {
      this.editDialogVisible = true
      this.editForm.username = username
    },
    // 监听修改密码对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮，修改用户密码
    editPwds () {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put('/user/setPwd/', {
          username: this.editForm.username,
          password: this.editForm.newpass
        })
        if (res.status !== 200) {
          return this.$message.error('更新用户密码失败!')
        }
        this.$message.success('更新用户密码成功！')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 展示修改学生用户姓名的对话框
    showNameDialog (id, username, role) {
      this.nameDialogVisible = true
      this.nameForm.id = id
      this.nameForm.username = username
      this.nameForm.role = role
    },
    // 监听修改姓名对话框的关闭事件
    nameDialogClosed () {
      this.$refs.nameFormRef.resetFields()
    },
    // 点击按钮，修改学生用户姓名
    editName () {
      this.$refs.nameFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/student/update/', {
          id: this.nameForm.id,
          username: this.nameForm.username,
          name: this.nameForm.name
        })
        if (res.status !== 200) {
          return this.$message.error('更新学生用户姓名失败!')
        }
        this.$message.success('更新学生用户姓名成功！')
        this.nameDialogVisible = false
      })
    },
    // 点击按钮，修改教师用户姓名
    editTechName () {
      this.$refs.nameFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/teacher/update/', {
          id: this.nameForm.id,
          teachId: this.nameForm.username,
          teachName: this.nameForm.name
        })
        if (res.status !== 200) {
          return this.$message.error('更新教师用户姓名失败!')
        }
        this.$message.success('更新教师用户姓名成功！')
        this.nameDialogVisible = false
      })
    },
    filterTag (value, row) {
      return row.role === value
    },
    handleCommand (command) {
      // this.$message('click on item ' + command)
      if (command === 'b') {
        this.Techopen = true
      }
      if (command === 'a') {
        this.Stuopen = true
      }
    },
    async getAllTechInfo () {
      const { data: res } = await this.$http.get('/teacher/all/')
      if (res.status !== 200) {
        return this.$message.error('获取教师信息失败!')
      }
      this.TechAllinfo = res.data
    },
    async getAllStuinfo () {
      const { data: res } = await this.$http.get('/student/allStudent/')
      if (res.status !== 200) {
        return this.$message.error('获取学生信息失败!')
      }
      this.StuAllinfo = res.data
    }
  },
  computed: {
    pageuserlist: function () {
      var search = this.queryInfo.searchInfo
      if (search) {
        return this.userlist.filter(function (data) {
          return Object.keys(data).some(function (key) {
            return String(data[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }
      return this.userlist.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
    }
  }
}
</script>

<style>
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
